require 'test/unit'
require 'observer'

require 'network/player_connection'
require 'network/handler'

class TCSocket
    include Observable
    def subscribe(o)
        add_observer(o)
    end
    def update(data)
        puts data
        $global = :socketio
    end
    def rcv(data='')
        changed
        notify_observers(data)
    end
end
class TCHandler
    def enter
        @handler_counter ||= 0
        @handler_counter += 1
    end
    def leave
        @handler_counter ||= 0
        @handler_counter -= 1
    end
    def handle(data)
        @handler_counter
    end
end
class PlayerConnection
    def update(data)
        $global = :playerio
        @handlers.top.handle(data) unless @handlers.empty?
    end
end

class ConnectionTest < Test::Unit::TestCase
    def setup
        @socket = TCSocket.new
    end
    def test_connection
        conn = PlayerConnection.new(@socket)

        conn.send_string("echo")
        assert_equal(:socketio,$global)

        @socket.rcv
        assert_equal(:playerio,$global)
    end

    def test_handlers
        conn = PlayerConnection.new(@socket)
        h = TCHandler.new
        conn.add_handler(h)
        assert_equal(1,h.handle(nil))
        conn.add_handler(h)
        assert_equal(2,h.handle(nil))

        conn.switch_handler(h)
        assert_equal(2,h.handle(nil))

        conn.del_handler
        # leave 2 - 1 = 1
        # enter 1 + 1 = 2
        assert_equal(2,h.handle(nil))

        conn.del_handler
        assert_equal(1,h.handle(nil))
    end

    def test_logon_handler
        conn = PlayerConnection.new(@socket)
        h = LogonHandler.new(conn)
        conn.add_handler(h)

        @socket.rcv('initdone')
    end
end
